﻿using Edu.EntityFrameworkCore;
using Edu.Localization.Edu;
using Edu.Menus;
using Edu.Permissions;
using Localization.Resources.AbpUi;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Swashbuckle.AspNetCore.Swagger;
using System.Text;
using Volo.Abp;
using Volo.Abp.Account.Web;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.AspNetCore.Mvc.Localization;
using Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared;
using Volo.Abp.Autofac;
using Volo.Abp.AutoMapper;
using Volo.Abp.Data;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.Extension.Web;
using Volo.Abp.Identity;
using Volo.Abp.Identity.AspNetCore;
using Volo.Abp.Identity.Web;
using Volo.Abp.Localization;
using Volo.Abp.Localization.Resources.AbpValidation;
using Volo.Abp.Modularity;
using Volo.Abp.TenantManagement.Web;
using Volo.Abp.Threading;
using Volo.Abp.UI.Navigation;


namespace Edu
{
    [DependsOn(
        typeof(EduApplicationModule),
        typeof(EduEntityFrameworkCoreModule),
        typeof(AbpAutofacModule),
        typeof(AbpIdentityWebModule),
        typeof(AbpAccountWebModule),
        typeof(AbpTenantManagementWebModule),
        typeof(VoloAbpExtensionWebModule)
        )]
    public class EduWebModule : AbpModule
    {
        public override void PreConfigureServices(ServiceConfigurationContext context)
        {
            context.Services.PreConfigure<AbpMvcDataAnnotationsLocalizationOptions>(options =>
            {
                options.AddAssemblyResource(
                    typeof(EduResource),
                    typeof(EduDomainModule).Assembly,
                    typeof(EduApplicationModule).Assembly,
                    typeof(EduWebModule).Assembly
                );
            });

            context.Services.PreConfigure<AbpIdentityAspNetCoreOptions>(options =>
            {
                options.ConfigureAuthentication = false;
            });
        }

        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var hostingEnvironment = context.Services.GetHostingEnvironment();
            var configuration = context.Services.GetConfiguration();

            ConfigureDatabaseServices();
            ConfigureAutoMapper();
            ConfigureVirtualFileSystem(hostingEnvironment);
            ConfigureLocalizationServices();
            ConfigureNavigationServices();
            ConfigureAutoApiControllers();
            ConfigureSwaggerServices(context.Services);
            ConfigureAuthentication(context.Services, configuration);


            this.Configure<ExcelOptions>(configuration.GetSection("Excel"));


            Configure<RazorPagesOptions>(options =>
            {
                options.Conventions.AuthorizePage("/Index", IdentityPermissions.Users.Default);
                options.Conventions.AuthorizePage("/SettingManagement/Index", IdentityPermissions.Users.Default);

                options.Conventions.AuthorizePage("/Achievement/Index", AchievementPermissions.Default);
                options.Conventions.AuthorizePage("/Achievement/Delete", AchievementPermissions.Delete);
                options.Conventions.AuthorizePage("/Achievement/Update", AchievementPermissions.Update);

                options.Conventions.AuthorizePage("/UserAchievement/Index", UserAchievementPermissions.Default);
                options.Conventions.AuthorizePage("/UserAchievement/Delete", UserAchievementPermissions.Delete);
                options.Conventions.AuthorizePage("/UserAchievement/Update", UserAchievementPermissions.Update);

                options.Conventions.AuthorizePage("/StudyTask/Index", StudyTaskPermissions.Default);
                options.Conventions.AuthorizePage("/StudyTask/Delete", StudyTaskPermissions.Delete);
                options.Conventions.AuthorizePage("/StudyTask/Update", StudyTaskPermissions.Update);
            });
        }

        private void ConfigureAuthentication(IServiceCollection services, IConfigurationRoot configuration)
        {
            services.AddCors();
            var jwtOptionSection = configuration.GetSection("JWT");
            services.Configure<JWTOptions>(jwtOptionSection);

            // configure jwt authentication
            var jwtOptions = jwtOptionSection.Get<JWTOptions>();
            var key = Encoding.ASCII.GetBytes(jwtOptions.Secret);


            services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.Lax;
            });



            var authenticationBuilder = services.AddAuthentication(o =>
                {
                    o.DefaultScheme = IdentityConstants.ApplicationScheme;
                    o.DefaultSignInScheme = IdentityConstants.ExternalScheme;
                });
            authenticationBuilder.AddIdentityCookies();
            authenticationBuilder.AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });
        }

        private void ConfigureDatabaseServices()
        {
            Configure<AbpDbContextOptions>(options =>
            {
                options.UseMySQL();
            });
        }

        private void ConfigureAutoMapper()
        {
            Configure<AbpAutoMapperOptions>(options =>
            {
                options.AddProfile<EduWebAutoMapperProfile>();
            });
        }

        private void ConfigureVirtualFileSystem(IHostingEnvironment hostingEnvironment)
        {
            if (hostingEnvironment.IsDevelopment())
            {

            }
        }

        private void ConfigureLocalizationServices()
        {
            Configure<AbpLocalizationOptions>(options =>
            {
                options.Resources
                    .Get<EduResource>()
                    .AddBaseTypes(
                        typeof(AbpValidationResource),
                        typeof(AbpUiResource)
                    );
            });
        }

        private void ConfigureNavigationServices()
        {
            Configure<NavigationOptions>(options =>
            {
                options.MenuContributors.Add(new EduMenuContributor());
            });
        }

        private void ConfigureAutoApiControllers()
        {
            Configure<AbpAspNetCoreMvcOptions>(options =>
            {
                options.ConventionalControllers.Create(typeof(EduApplicationModule).Assembly);
            });
        }

        private void ConfigureSwaggerServices(IServiceCollection services)
        {
            services.AddSwaggerGen(
                options =>
                {
                    options.SwaggerDoc("v1", new Info { Title = "Edu API", Version = "v1" });
                    options.DocInclusionPredicate((docName, description) => true);
                    options.CustomSchemaIds(type => type.FullName);
                });
        }

        public override void OnApplicationInitialization(ApplicationInitializationContext context)
        {
            var app = context.GetApplicationBuilder();
            var env = context.GetEnvironment();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseErrorPage();//会跳转到Error?httpStatusCode={0}页面
            }
            // global cors policy
            app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());

            app.UseCookiePolicy();

            app.UseVirtualFiles();
            app.UseAuthentication();

            if (EduConsts.IsMultiTenancyEnabled)
            {
                app.UseMultiTenancy();
            }

            app.UseAbpRequestLocalization();

            app.UseSwagger();
            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint("/swagger/v1/swagger.json", "Edu API");
            });

            app.UseAuditing();

            app.UseMvcWithDefaultRouteAndArea();

            SeedDatabase(context);
        }


        /// <summary>
        /// 参见IdentityDataSeeder..主要是添加admin账号
        /// </summary>
        /// <param name="context"></param>
        private static void SeedDatabase(ApplicationInitializationContext context)
        {
            using (var scope = context.ServiceProvider.CreateScope())
            {
                AsyncHelper.RunSync(async () =>
                {
                    await scope.ServiceProvider
                        .GetRequiredService<IDataSeeder>()
                        .SeedAsync();
                });
            }
        }
    }


    public class ExcelOptions
    {
        public string Path { get; set; }
    }
}
